import { ipcMain } from 'electron'

let mainWindow = null

function setMsgMainWindow(window) {
  if (mainWindow){
    return
  }
  mainWindow = window
}

function sendSocketMsg(msgType, message) {
  if (mainWindow && !mainWindow.isDestroyed()) {
    message.time = new Date().toLocaleString();
    mainWindow.webContents.send(msgType, message)
  }
}

let websocket = null // 定义 WebSocket 实例

ipcMain.handle('openWebsocket', async (event, webSocketUrl) => {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    console.log('WebSocket 已经打开')
    return
  }
  websocket = new WebSocket(webSocketUrl)
  websocket.onopen = () => {
    console.log('WebSocket 连接已打开')
    sendSocketMsg('socket-msg-from-main', { type: 'system', content: '连接已建立' })
  }
  websocket.onmessage = (event) => {
    sendSocketMsg('socket-msg-from-main', { type: 'receive', content: event.data })
  }
  websocket.onclose = () => {
    console.log('WebSocket 连接已关闭')
    sendSocketMsg('socket-msg-from-main', { type: 'system', content: '连接已关闭' })
  }
  websocket.onerror = (error) => {
    console.error('WebSocket 错误:', error)
    sendSocketMsg('socket-msg-from-main', { type: 'system', content: '连接错误' })
  }
})

ipcMain.handle('closeWebsocket', async () => {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    websocket.close()
  }
})

ipcMain.handle('getWebsocketStatus', async () => {
  console.log('获取websocket状态')
  return websocket && websocket.readyState === WebSocket.OPEN
})

ipcMain.handle('sendWebsocketMsg', async (event, sendContent) => {
  if (websocket && websocket.readyState === WebSocket.OPEN) {
    websocket.send(sendContent)
    sendSocketMsg('socket-msg-from-main', { type: 'send', content: sendContent })
  } else {
    sendSocketMsg('socket-msg-from-main', { type: 'system', content: '请先连接 WebSocket' })
  }
})

export { setMsgMainWindow, sendSocketMsg }
